Chartist - API Documentation

auto-scale-axis.js

Module Chartist.AutoScaleAxis

The auto scale axis uses standard linear scale projection of values along an axis. It uses order of magnitude to find a scale automatically and evaluates the available space in order to find the perfect amount of ticks for your chart.
Options
The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.

var options = {
  // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
  high: 100,
  // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
  low: 0,
  // This option will be used when finding the right scale division settings. The amount of ticks on the scale will be determined so that as many ticks as possible will be displayed, while not violating this minimum required space (in pixel).
  scaleMinSpace: 20,
  // Can be set to true or false. If set to true, the scale will be generated with whole numbers only.
  onlyInteger: true,
  // The reference value can be used to make sure that this value will always be on the chart. This is especially useful on bipolar charts where the bipolar center always needs to be part of the chart.
  referenceValue: 5
};

axis.js

fixed-scale-axis.js

Module Chartist.FixedScaleAxis

The fixed scale axis uses standard linear projection of values along an axis. It makes use of a divisor option to divide the range provided from the minimum and maximum value or the options high and low that will override the computed minimum and maximum.
Options
The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.

var options = {
  // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
  high: 100,
  // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
  low: 0,
  // If specified then the value range determined from minimum to maximum (or low and high) will be divided by this number and ticks will be generated at those division points. The default divisor is 1.
  divisor: 4,
  // If ticks is explicitly set, then the axis will not compute the ticks with the divisor, but directly use the data in ticks to determine at what points on the axis a tick need to be generated.
  ticks: [1, 10, 20, 30]
};

step-axis.js

Module Chartist.StepAxis

The step axis for step based charts like bar chart or step based line charts. It uses a fixed amount of ticks that will be equally distributed across the whole axis length. The projection is done using the index of the data value rather than the value itself and therefore it's only useful for distribution purpose.
Options
The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.

var options = {
  // Ticks to be used to distribute across the axis length. As this axis type relies on the index of the value rather than the value, arbitrary data that can be converted to a string can be used as ticks.
  ticks: ['One', 'Two', 'Three'],
  // If set to true the full width will be used to distribute the values where the last value will be at the maximum of the axis length. If false the spaces between the ticks will be evenly distributed instead.
  stretch: true
};

base.js

Module Chartist.Base

Base for all chart types. The methods in Chartist.Base are inherited to all chart types.

function update()

Updates the chart which currently does a full reconstruction of the SVG DOM

Parameters
[data] ( Object )
Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.
[options] ( Object )
Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart.
[override] ( Boolean )
If set to true, the passed options will be used to extend the options that have been configured already. Otherwise the chart default options will be used as the base
function detach()

This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.

function on()

Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.

Parameters
event ( String )
Name of the event. Check the examples for supported events.
handler ( Function )
The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.
function off()

Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.

Parameters
event ( String )
Name of the event for which a handler should be removed
[handler] ( Function )
The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.

bar.js

Module Chartist.Bar

The bar chart module of Chartist that can be used to draw unipolar or bipolar bar and grouped bar charts.

declaration defaultOptions

Default options in bar charts. Expand the code view to see a detailed list of options with comments.

function Bar()

This method creates a new bar chart and returns API object that you can use for later changes.

Parameters
query ( String Node )
A selector query string or directly a DOM element
data ( Object )
The data object that needs to consist of a labels and a series array
[options] ( Object )
The options object with options that override the default options. Check the examples for a detailed list.
[responsiveOptions] ( Array )
Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
Returns
( Object )
An object which exposes the API for the created chart
Examples
// Create a simple bar chart
var data = {
  labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  series: [
    [5, 2, 4, 2, 0]
  ]
};

// In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object.
new Chartist.Bar('.ct-chart', data);
// This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10
new Chartist.Bar('.ct-chart', {
  labels: [1, 2, 3, 4, 5, 6, 7],
  series: [
    [1, 3, 2, -5, -3, 1, -6],
    [-5, -2, -4, -1, 2, -3, 1]
  ]
}, {
  seriesBarDistance: 12,
  low: -10,
  high: 10
});

line.js

Module Chartist.Line

The Chartist line chart can be used to draw Line or Scatter charts. If used in the browser you can access the global Chartist namespace where you find the Line function as a main entry point.

declaration defaultOptions

Default options in line charts. Expand the code view to see a detailed list of options with comments.

function Line()

This method creates a new line chart.

Parameters
query ( String Node )
A selector query string or directly a DOM element
data ( Object )
The data object that needs to consist of a labels and a series array
[options] ( Object )
The options object with options that override the default options. Check the examples for a detailed list.
[responsiveOptions] ( Array )
Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
Returns
( Object )
An object which exposes the API for the created chart
Examples
// Create a simple line chart
var data = {
  // A labels array that can contain any sort of values
  labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  // Our series array that contains series objects or in this case series data arrays
  series: [
    [5, 2, 4, 2, 0]
  ]
};

// As options we currently only set a static size of 300x200 px
var options = {
  width: '300px',
  height: '200px'
};

// In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options
new Chartist.Line('.ct-chart', data, options);
// Use specific interpolation function with configuration from the Chartist.Interpolation module

var chart = new Chartist.Line('.ct-chart', {
  labels: [1, 2, 3, 4, 5],
  series: [
    [1, 1, 8, 1, 7]
  ]
}, {
  lineSmooth: Chartist.Interpolation.cardinal({
    tension: 0.2
  })
});
// Create a line chart with responsive options

var data = {
  // A labels array that can contain any sort of values
  labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
  // Our series array that contains series objects or in this case series data arrays
  series: [
    [5, 2, 4, 2, 0]
  ]
};

// In addition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries.
var responsiveOptions = [
  ['screen and (min-width: 641px) and (max-width: 1024px)', {
    showPoint: false,
    axisX: {
      labelInterpolationFnc: function(value) {
        // Will return Mon, Tue, Wed etc. on medium screens
        return value.slice(0, 3);
      }
    }
  }],
  ['screen and (max-width: 640px)', {
    showLine: false,
    axisX: {
      labelInterpolationFnc: function(value) {
        // Will return M, T, W etc. on small screens
        return value[0];
      }
    }
  }]
];

new Chartist.Line('.ct-chart', data, null, responsiveOptions);

pie.js

Module Chartist.Pie

The pie chart module of Chartist that can be used to draw pie, donut or gauge charts

declaration defaultOptions

Default options in line charts. Expand the code view to see a detailed list of options with comments.

function Pie()

This method creates a new pie chart and returns an object that can be used to redraw the chart.

Parameters
query ( String Node )
A selector query string or directly a DOM element
data ( Object )
The data object in the pie chart needs to have a series property with a one dimensional data array. The values will be normalized against each other and don't necessarily need to be in percentage. The series property can also be an array of value objects that contain a value property and a className property to override the CSS class name for the series group.
[options] ( Object )
The options object with options that override the default options. Check the examples for a detailed list.
[responsiveOptions] ( Array )
Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
Returns
( Object )
An object with a version and an update method to manually redraw the chart
Examples
// Simple pie chart example with four series
new Chartist.Pie('.ct-chart', {
  series: [10, 2, 4, 3]
});
// Drawing a donut chart
new Chartist.Pie('.ct-chart', {
  series: [10, 2, 4, 3]
}, {
  donut: true
});
// Using donut, startAngle and total to draw a gauge chart
new Chartist.Pie('.ct-chart', {
  series: [20, 10, 30, 40]
}, {
  donut: true,
  donutWidth: 20,
  startAngle: 270,
  total: 200
});
// Drawing a pie chart with padding and labels that are outside the pie
new Chartist.Pie('.ct-chart', {
  series: [20, 10, 30, 40]
}, {
  chartPadding: 30,
  labelOffset: 50,
  labelDirection: 'explode'
});
// Overriding the class names for individual series as well as a name and meta data.
// The name will be written as ct:series-name attribute and the meta data will be serialized and written
// to a ct:meta attribute.
new Chartist.Pie('.ct-chart', {
  series: [{
    value: 20,
    name: 'Series 1',
    className: 'my-custom-class-one',
    meta: 'Meta One'
  }, {
    value: 10,
    name: 'Series 2',
    className: 'my-custom-class-two',
    meta: 'Meta Two'
  }, {
    value: 70,
    name: 'Series 3',
    className: 'my-custom-class-three',
    meta: 'Meta Three'
  }]
});

class.js

Module Chartist.Class

This module provides some basic prototype inheritance utilities.

function extend()

Method to extend from current prototype.

Parameters
properties ( Object )
The object that serves as definition for the prototype that gets created for the new class. This object should always contain a constructor property that is the desired constructor for the newly created class.
[superProtoOverride] ( Object )
By default extens will use the current class prototype or Chartist.class. With this parameter you can specify any super prototype that will be used.
Returns
( Function )
Constructor function of the new class
Examples
var Fruit = Class.extend({
color: undefined,
  sugar: undefined,

  constructor: function(color, sugar) {
    this.color = color;
    this.sugar = sugar;
  },

  eat: function() {
    this.sugar = 0;
    return this;
  }
});

var Banana = Fruit.extend({
  length: undefined,

  constructor: function(length, sugar) {
    Banana.super.constructor.call(this, 'Yellow', sugar);
    this.length = length;
  }
});

var banana = new Banana(20, 40);
console.log('banana instanceof Fruit', banana instanceof Fruit);
console.log('Fruit is prototype of banana', Fruit.prototype.isPrototypeOf(banana));
console.log('bananas prototype is Fruit', Object.getPrototypeOf(banana) === Fruit.prototype);
console.log(banana.sugar);
console.log(banana.eat().sugar);
console.log(banana.color);

core.js

Module Chartist.Core

The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.

property Chartist.namespaces

This object contains all namespaces used within Chartist.

method Chartist.times()

Functional style helper to produce array with given length initialized with undefined values

Parameters
( length )
Returns
( Array )
method Chartist.sum()

Sum helper to be used in reduce functions

Parameters
( previous )
( current )
Returns
( * )
method Chartist.mapMultiply()

Multiply helper to be used in Array.map for multiplying each value of an array with a factor.

Parameters
factor ( Number )
method Chartist.mapAdd()

Add helper to be used in Array.map for adding a addend to each value of an array.

Parameters
addend ( Number )
method Chartist.serialMap()

Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).

Parameters
( arr )
( cb )
Returns
( Array )
method Chartist.roundWithPrecision()

This helper function can be used to round values with certain precision level after decimal. This is used to prevent rounding errors near float point precision limit.

Parameters
value ( Number )
The value that should be rounded with precision
[digits] ( Number )
The number of digits after decimal used to do the rounding
property Chartist.precision

Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.

property Chartist.escapingMap

A map with characters to escape for strings to be safely used as attribute values.

method Chartist.serialize()

This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap.
If called with null or undefined the function will return immediately with null or undefined.

Parameters
data ( Number String Object )
Returns
( String )
method Chartist.deserialize()

This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.

Parameters
data ( String )
Returns
( String Number Object )
method Chartist.createSvg()

Create or reinitialize the SVG element for the chart

Parameters
container ( Node )
The containing DOM Node object that will be used to plant the SVG element
width ( String )
Set the width of the SVG element. Default is 100%
height ( String )
Set the height of the SVG element. Default is 100%
className ( String )
Specify a class to be added to the SVG element
Returns
( Object )
The created/reinitialized SVG element
method Chartist.reverseData()

Reverses the series, labels and series data arrays.

Parameters
( data )
method Chartist.getDataArray()

Convert data series into plain array

Parameters
data ( Object )
The series object that contains the data to be visualized in the chart
[reverse] ( Boolean )
If true the whole data is reversed by the getDataArray call. This will modify the data object passed as first parameter. The labels as well as the series order is reversed. The whole series data arrays are reversed too.
[multi] ( Boolean )
Create a multi dimensional array from a series data array where a value object with `x` and `y` values will be created.
Returns
( Array )
A plain array that contains the data to be visualized in the chart
method Chartist.normalizePadding()

Converts a number into a padding object.

Parameters
padding ( Object Number )
[fallback] ( Number )
This value is used to fill missing values if a incomplete padding object was passed
method Chartist.orderOfMagnitude()

Calculate the order of magnitude for the chart scale

Parameters
value ( Number )
The value Range of the chart
Returns
( Number )
The order of magnitude
method Chartist.projectLength()

Project a data length into screen coordinates (pixels)

Parameters
axisLength ( Object )
The svg element for the chart
length ( Number )
Single data value from a series array
bounds ( Object )
All the values to set the bounds of the chart
Returns
( Number )
The projected data length in pixels
method Chartist.getAvailableHeight()

Get the height of the area in the chart for the data series

Parameters
svg ( Object )
The svg element for the chart
options ( Object )
The Object that contains all the optional values for the chart
Returns
( Number )
The height of the area in the chart for the data series
method Chartist.getHighLow()

Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.

Parameters
data ( Array )
The array that contains the data to be visualized in the chart
options ( Object )
The Object that contains the chart options
dimension ( String )
Axis dimension 'x' or 'y' used to access the correct value and high / low configuration
Returns
( Object )
An object that contains the highest and lowest value that will be visualized on the chart.
method Chartist.isNumeric()

Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite.

Parameters
( value )
method Chartist.isFalseyButZero()

Returns true on all falsey values except the numeric value 0.

Parameters
( value )
method Chartist.getNumberOrUndefined()

Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined.

Parameters
( value )
method Chartist.isMultiValue()

Checks if provided value object is multi value (contains x or y properties)

Parameters
( value )
method Chartist.getMultiValue()

Gets a value from a dimension value.x or value.y while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return defaultValue.

Parameters
( value )
( dimension )
( defaultValue )
method Chartist.rho()

Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex.

Parameters
num ( Number )
An integer number where the smallest factor should be searched for
method Chartist.getBounds()

Calculate and retrieve all the bounds for the chart and return them in one array

Parameters
axisLength ( Number )
The length of the Axis used for
highLow ( Object )
An object containing a high and low property indicating the value range of the chart.
scaleMinSpace ( Number )
The minimum projected length a step should result in
onlyInteger ( Boolean )
Returns
( Object )
All the values to set the bounds of the chart
method Chartist.polarToCartesian()

Calculate cartesian coordinates of polar coordinates

Parameters
centerX ( Number )
X-axis coordinates of center point of circle segment
centerY ( Number )
X-axis coordinates of center point of circle segment
radius ( Number )
Radius of circle segment
angleInDegrees ( Number )
Angle of circle segment in degrees
Returns
( x:Number )
y:Number}} Coordinates of point on circumference
method Chartist.createChartRect()

Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right

Parameters
svg ( Object )
The svg element for the chart
options ( Object )
The Object that contains all the optional values for the chart
[fallbackPadding] ( Number )
The fallback padding if partial padding objects are used
Returns
( Object )
The chart rectangles coordinates inside the svg element plus the rectangles measurements
method Chartist.createGrid()

Creates a grid line based on a projected value.

Parameters
( position )
( index )
( axis )
( offset )
( length )
( group )
( classes )
( eventEmitter )
method Chartist.createGridBackground()

Creates a grid background rect and emits the draw event.

Parameters
( gridGroup )
( chartRect )
( className )
( eventEmitter )
method Chartist.createLabel()

Creates a label based on a projected value and an axis.

Parameters
( position )
( length )
( index )
( labels )
( axis )
( axisOffset )
( labelOffset )
( group )
( classes )
( useForeignObject )
( eventEmitter )
method Chartist.optionsProvider()

Provides options handling functionality with callback for options changes triggered by responsive options and media query matches

Parameters
options ( Object )
Options set by user
responsiveOptions ( Array )
Optional functions to add responsive behavior to chart
eventEmitter ( Object )
The event emitter that will be used to emit the options changed events
Returns
( Object )
The consolidated options object from the defaults, base and matching responsive options

event.js

Module Chartist.Event

A very basic event module that helps to generate and catch events.

function addEventHandler()

Add an event handler for a specific event

Parameters
event ( String )
The event name
handler ( Function )
A event handler function
function removeEventHandler()

Remove an event handler of a specific event name or remove all event handlers for a specific event.

Parameters
event ( String )
The event name where a specific or all handlers should be removed
[handler] ( Function )
An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed.
function emit()

Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.

Parameters
event ( String )
The event name that should be triggered
data ( * )
Arbitrary data that will be passed to the event handler callback functions

interpolation.js

Module Chartist.Interpolation

Chartist path interpolation functions.

method Chartist.Interpolation.none()

This interpolation function does not smooth the path and the result is only containing lines and no curves.

Returns
( Function )
Examples
var chart = new Chartist.Line('.ct-chart', {
  labels: [1, 2, 3, 4, 5],
  series: [[1, 2, 8, 1, 7]]
}, {
  lineSmooth: Chartist.Interpolation.none({
    fillHoles: false
  })
});

method Chartist.Interpolation.simple()

Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing.

Parameters
options ( Object )
The options of the simple interpolation factory function.
Returns
( Function )
Examples
var chart = new Chartist.Line('.ct-chart', {
  labels: [1, 2, 3, 4, 5],
  series: [[1, 2, 8, 1, 7]]
}, {
  lineSmooth: Chartist.Interpolation.simple({
    divisor: 2,
    fillHoles: false
  })
});

method Chartist.Interpolation.cardinal()

Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results.

Parameters
options ( Object )
The options of the cardinal factory function.
Returns
( Function )
Examples
var chart = new Chartist.Line('.ct-chart', {
  labels: [1, 2, 3, 4, 5],
  series: [[1, 2, 8, 1, 7]]
}, {
  lineSmooth: Chartist.Interpolation.cardinal({
    tension: 1,
    fillHoles: false
  })
});
method Chartist.Interpolation.monotoneCubic()

Monotone Cubic spline interpolation produces a smooth curve which preserves monotonicity. Unlike cardinal splines, the curve will not extend beyond the range of y-values of the original data points.

Parameters
options ( Object )
The options of the monotoneCubic factory function.
Returns
( Function )
Examples
var chart = new Chartist.Line('.ct-chart', {
  labels: [1, 2, 3, 4, 5],
  series: [[1, 2, 8, 1, 7]]
}, {
  lineSmooth: Chartist.Interpolation.monotoneCubic({
    fillHoles: false
  })
});
method Chartist.Interpolation.step()

Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the showPoint option is enabled.

Parameters
( options )
Examples
var chart = new Chartist.Line('.ct-chart', {
  labels: [1, 2, 3, 4, 5],
  series: [[1, 2, 8, 1, 7]]
}, {
  lineSmooth: Chartist.Interpolation.step({
    postpone: true,
    fillHoles: false
  })
});

svg-path.js

Module Chartist.Svg.Path

Chartist SVG path module for SVG path description creation and modification.

declaration elementDescriptions

Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported.

declaration defaultOptions

Default options for newly created SVG path objects.

constructor SvgPath()

Used to construct a new path object.

Parameters
close ( Boolean )
If set to true then this path will be closed when stringified (with a Z at the end)
options ( Object )
Options object that overrides the default objects. See default options for more details.
function position()

Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor.

Parameters
[pos] ( Number )
If a number is passed then the cursor is set to this position in the path element array.
Returns
( Chartist.Svg.Path Number )
If the position parameter was passed then the return value will be the path object for easy call chaining. If no position parameter was passed then the current position is returned.
function remove()

Removes elements from the path starting at the current position.

Parameters
count ( Number )
Number of path elements that should be removed from the current position.
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function move()

Use this function to add a new move SVG path element.

Parameters
x ( Number )
The x coordinate for the move element.
y ( Number )
The y coordinate for the move element.
[relative] ( Boolean )
If set to true the move element will be created with relative coordinates (lowercase letter)
[data] ( * )
Any data that should be stored with the element object that will be accessible in pathElement
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function line()

Use this function to add a new line SVG path element.

Parameters
x ( Number )
The x coordinate for the line element.
y ( Number )
The y coordinate for the line element.
[relative] ( Boolean )
If set to true the line element will be created with relative coordinates (lowercase letter)
[data] ( * )
Any data that should be stored with the element object that will be accessible in pathElement
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function curve()

Use this function to add a new curve SVG path element.

Parameters
x1 ( Number )
The x coordinate for the first control point of the bezier curve.
y1 ( Number )
The y coordinate for the first control point of the bezier curve.
x2 ( Number )
The x coordinate for the second control point of the bezier curve.
y2 ( Number )
The y coordinate for the second control point of the bezier curve.
x ( Number )
The x coordinate for the target point of the curve element.
y ( Number )
The y coordinate for the target point of the curve element.
[relative] ( Boolean )
If set to true the curve element will be created with relative coordinates (lowercase letter)
[data] ( * )
Any data that should be stored with the element object that will be accessible in pathElement
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function arc()

Use this function to add a new non-bezier curve SVG path element.

Parameters
rx ( Number )
The radius to be used for the x-axis of the arc.
ry ( Number )
The radius to be used for the y-axis of the arc.
xAr ( Number )
Defines the orientation of the arc
lAf ( Number )
Large arc flag
sf ( Number )
Sweep flag
x ( Number )
The x coordinate for the target point of the curve element.
y ( Number )
The y coordinate for the target point of the curve element.
[relative] ( Boolean )
If set to true the curve element will be created with relative coordinates (lowercase letter)
[data] ( * )
Any data that should be stored with the element object that will be accessible in pathElement
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function parse()

Parses an SVG path seen in the d attribute of path elements, and inserts the parsed elements into the existing path object at the current cursor position. Any closing path indicators (Z at the end of the path) will be ignored by the parser as this is provided by the close option in the options of the path object.

Parameters
path ( String )
Any SVG path that contains move (m), line (l) or curve (c) components.
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function stringify()

This function renders to current SVG path object into a final SVG string that can be used in the d attribute of SVG path elements. It uses the accuracy option to round big decimals. If the close parameter was set in the constructor of this path object then a path closing Z will be appended to the output string.

Returns
( String )
function scale()

Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves, affecting the given coordinate.

Parameters
x ( Number )
The number which will be used to scale the x, x1 and x2 of all path elements.
y ( Number )
The number which will be used to scale the y, y1 and y2 of all path elements.
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function translate()

Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate.

Parameters
x ( Number )
The number which will be used to translate the x, x1 and x2 of all path elements.
y ( Number )
The number which will be used to translate the y, y1 and y2 of all path elements.
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function transform()

This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path.
The method signature of the callback function looks like this:

function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)

If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate.

Parameters
transformFnc ( Function )
The callback function for the transformation. Check the signature in the function description.
Returns
( Chartist.Svg.Path )
The current path object for easy call chaining.
function clone()

This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.

Parameters
[close] ( Boolean )
Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used.
Returns
( Chartist.Svg.Path )
function splitByCommand()

Split a Svg.Path object by a specific command in the path chain. The path chain will be split and an array of newly created paths objects will be returned. This is useful if you'd like to split an SVG path by it's move commands, for example, in order to isolate chunks of drawings.

Parameters
command ( String )
The command you'd like to use to split the path
Returns
( Array<Chartist.Svg.Path> )
function join()

This static function on Chartist.Svg.Path is joining multiple paths together into one paths.

Parameters
paths ( Array<Chartist.Svg.Path> )
A list of paths to be joined together. The order is important.
close ( boolean )
If the newly created path should be a closed path
options ( Object )
Path options for the newly created path.
Returns
( Chartist.Svg.Path )

svg.js

Module Chartist.Svg

Chartist SVG module for simple SVG DOM abstraction

constructor Svg()

Chartist.Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them.

Parameters
name ( String Element )
The name of the SVG element to create or an SVG dom element which should be wrapped into Chartist.Svg
attributes ( Object )
An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
className ( String )
This class or class list will be added to the SVG element
parent ( Object )
The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child
insertFirst ( Boolean )
If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
function attr()

Set attributes on the current SVG element of the wrapper you're currently working on.

Parameters
attributes ( Object String )
An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value.
[ns] ( String )
If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object.
Returns
( Object String )
The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function.
function elem()

Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.

Parameters
name ( String )
The name of the SVG element that should be created as child element of the currently selected element wrapper
[attributes] ( Object )
An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
[className] ( String )
This class or class list will be added to the SVG element
[insertFirst] ( Boolean )
If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
Returns
( Chartist.Svg )
Returns a Chartist.Svg wrapper object that can be used to modify the containing SVG data
function parent()

Returns the parent Chartist.SVG wrapper object

Returns
( Chartist.Svg )
Returns a Chartist.Svg wrapper around the parent node of the current node. If the parent node is not existing or it's not an SVG node then this function will return null.
function root()

This method returns a Chartist.Svg wrapper around the root SVG element of the current tree.

Returns
( Chartist.Svg )
The root SVG element wrapped in a Chartist.Svg element
function querySelector()

Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper.

Parameters
selector ( String )
A CSS selector that is used to query for child SVG elements
Returns
( Chartist.Svg )
The SVG wrapper for the element found or null if no element was found
function querySelectorAll()

Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper.

Parameters
selector ( String )
A CSS selector that is used to query for child SVG elements
Returns
( Chartist.Svg.List )
The SVG wrapper list for the element found or null if no element was found
function getNode()

Returns the underlying SVG node for the current element.

function foreignObject()

This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM.

Parameters
content ( Node String )
The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject
[attributes] ( String )
An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added.
[className] ( String )
This class or class list will be added to the SVG element
[insertFirst] ( Boolean )
Specifies if the foreignObject should be inserted as first child
Returns
( Chartist.Svg )
New wrapper object that wraps the foreignObject element
function text()

This method adds a new text element to the current Chartist.Svg wrapper.

Parameters
t ( String )
The text that should be added to the text element that is created
Returns
( Chartist.Svg )
The same wrapper object that was used to add the newly created element
function empty()

This method will clear all child nodes of the current wrapper object.

Returns
( Chartist.Svg )
The same wrapper object that got emptied
function remove()

This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure.

Returns
( Chartist.Svg )
The parent wrapper object of the element that got removed
function replace()

This method will replace the element with a new element that can be created outside of the current DOM.

Parameters
newElement ( Chartist.Svg )
The new Chartist.Svg object that will be used to replace the current wrapper object
Returns
( Chartist.Svg )
The wrapper of the new element
function append()

This method will append an element to the current element as a child.

Parameters
element ( Chartist.Svg )
The Chartist.Svg element that should be added as a child
[insertFirst] ( Boolean )
Specifies if the element should be inserted as first child
Returns
( Chartist.Svg )
The wrapper of the appended object
function classes()

Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.

Returns
( Array )
A list of classes or an empty array if there are no classes on the current element
function addClass()

Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.

Parameters
names ( String )
A white space separated list of class names
Returns
( Chartist.Svg )
The wrapper of the current element
function removeClass()

Removes one or a space separated list of classes from the current element.

Parameters
names ( String )
A white space separated list of class names
Returns
( Chartist.Svg )
The wrapper of the current element
function removeAllClasses()

Removes all classes from the current element.

Returns
( Chartist.Svg )
The wrapper of the current element
function height()

Get element height using getBoundingClientRect

Returns
( Number )
The elements height in pixels
function animate()

The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in Chartist.Svg.Easing or an array with four numbers specifying a cubic Bézier curve.
An animations object could look like this:

element.animate({
  opacity: {
    dur: 1000,
    from: 0,
    to: 1
  },
  x1: {
    dur: '1000ms',
    from: 100,
    to: 200,
    easing: 'easeOutQuart'
  },
  y1: {
    dur: '2s',
    from: 0,
    to: 100
  }
});

Automatic unit conversion
For the dur and the begin animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds.
Guided mode
The default behavior of SMIL animations with offset using the begin attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation from value even before the animation starts. Also if you don't specify fill="freeze" on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Chartist.Svg will also use the begin property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it.
If guided mode is enabled the following behavior is added:

  • Before the animation starts (even when delayed with begin) the animated attribute will be set already to the from value of the animation
  • begin is explicitly set to indefinite so it can be started manually without relying on document begin time (creation)
  • The animate element will be forced to use fill="freeze"
  • The animation will be triggered with beginElement() in a timeout where begin of the definition object is interpreted in milli seconds. If no begin was specified the timeout is triggered immediately.
  • After the animation the element attribute value will be set to the to value of the animation
  • The animate element is deleted from the DOM
Parameters
animations ( Object )
An animations object where the property keys are the attributes you'd like to animate. The properties should be objects again that contain the SMIL animation attributes (usually begin, dur, from, and to). The property begin and dur is auto converted (see Automatic unit conversion). You can also schedule multiple animations for the same attribute by passing an Array of SMIL definition objects. Attributes that contain an array of SMIL definition objects will not be executed in guided mode.
guided ( Boolean )
Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated.
eventEmitter ( Object )
If specified, this event emitter will be notified when an animation starts or ends.
Returns
( Chartist.Svg )
The current element where the animation was added
method Chartist.Svg.isSupported()

This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list.

Parameters
feature ( String )
The SVG 1.1 feature that should be checked for support.
Returns
( Boolean )
True of false if the feature is supported or not